package per.turtle.auth.controller;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import per.turtle.auth.form.LoginBody;
import per.turtle.auth.service.SysLoginService;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.common.security.service.TokenService;
import per.turtle.system.dto.LoginUser;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * token 控制
 *
 * @author turtle
 */
@RequiredArgsConstructor
@RestController
public class TokenController {

    private final TokenService tokenService;

    private final SysLoginService sysLoginService;

    /**
     * 走的拦截器（此处仅为文档展示）
     */
    @ApiOperation("获取验证码")
    @GetMapping("code")
    public CommonResult<?> captcha() {
        return null;
    }

    @ApiOperation("登录")
    @PostMapping("login")
    public CommonResult<Map<String, Object>> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return CommonResult.success(tokenService.createToken(userInfo));
    }

    @ApiOperation("登出")
    @PostMapping("logout")
    public CommonResult<Void> logout(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (BeanUtil.isNotEmpty(loginUser)) {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return CommonResult.success();
    }

    @ApiOperation("刷新登录状态")
    @PostMapping("refresh")
    public CommonResult<Void> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (BeanUtil.isNotEmpty(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return CommonResult.success();
        }
        return CommonResult.success();
    }

}
